package org.airlink.persistence {
	import flash.filesystem.File;  
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import flex.persistence.EntityManager;
	import flex.persistence.EntityManagerFacade;
	import flex.persistence.EntityManagerFactory;
	import flex.persistence.exceptions.PersistenceException;
	
	import mx.charts.chartClasses.InstanceCache;
	import mx.core.mx_internal;
	
	import org.airlink.persistence.EntityManagerImpl;

	public class AirLink {
		public function AirLink() {
		}
		/**
		 * Initialisation des entityManagers
		 * L'initialisation se faisant de façon assynchrone, cette methode doit etre lancé dés l'initialisation de l'application
		 * Le plus tôt possible.
		 * Elle exploite le fichier persistence.xml qui doit être dans le repertoire de l'application
		 * LE XML doit ressembler à cela : 
		 * <?xml version="1.0" encoding="UTF-8"?>
		 * <persistence version="1.0">
		 *   <persistence-unit name="testPU">
		 *     <implementation>Flexorm.swf</implementation> MODULE FLex contenant l'implementation de fpa
		 *	   <userDirectory>c:\</userDirectory>   
		 *     <dbName>test.db</dbName> NOM de la base
		 *     <properties>
		 *       <!--property name="ddl-generation" value="drop-and-create-tables"/--> Mode de generation des tables
		 *       <property name="ddl-generation" value="create-tables"/>
		 *     </properties>
		 *   </persistence-unit>
		 * </persistence>
		 * Il peut y avoir plusieur persistenceUnit, mais les entités doivent être cloisonées dans un seul
		 */
		public static function initEntityManagers():void {
			var flag:Boolean=false;
			var initialized:Boolean = false;
			for(var key:String in flex.persistence.EntityManagerFactory.mx_internal::entityManagers) {
				initialized = true;
				break;
			}	
			if(!initialized) {
				var file:File = File.applicationDirectory.resolvePath("persistence.xml");
				if(!file.exists) throw new PersistenceException("file : 'persistence.xml' is required in application directory : "+File.applicationDirectory.nativePath);
				var fileStream:FileStream = null;
				try {
					fileStream = new FileStream(); 
					fileStream.open(file, FileMode.READ); 
					var persistence:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
					var list:XMLList = persistence.child("persistence-unit");
					var i:int = 0;
					for(; i<list.length(); i++) {
						var unitName:String = list[i].@["name"];
						if(!flex.persistence.EntityManagerFactory.mx_internal::entityManagers[unitName]) {
							flex.persistence.EntityManagerFactory.mx_internal::entityManagers[unitName] = new EntityManagerFacade();
							if(i==0) flex.persistence.EntityManagerFactory.mx_internal::entityManagers["default"] = flex.persistence.EntityManagerFactory.mx_internal::entityManagers[unitName]; 
							var persistenceUnitList:XMLList = persistence.child("persistence-unit").(@name == unitName);
							if(persistenceUnitList.length) {
								var persistenceUnit:XML = persistenceUnitList[0];
								var props:XML = null;
								var propsList:XMLList = persistenceUnit.properties;
								if(propsList && propsList.length()) props = propsList[0];
								if(persistenceUnit.factory == "org.airlink.persistence.EntityManagerFactory") {
									flex.persistence.EntityManagerFactory.mx_internal::entityManagers[unitName].mx_internal::implementation = EntityManagerImpl.getInstance(props) as EntityManager;
								}
							} else throw new PersistenceException("None persistenceUnit : "+unitName+" in persistence.xml");
						}
					} 
					if(i==0) throw new PersistenceException("None valid persistenceUnit in persistence.xml");
				} finally {
					if(fileStream) fileStream.close();
				}
			}
		}
	}
}